package com.guxuede.mina.chat;

import java.util.HashMap;

import org.apache.mina.core.session.IoSession;

public class ChatHall {
	private static HashMap<Long,ChatRoom> rooms;

	static {
		rooms=new HashMap<Long, ChatRoom>();
		createRoom(0L);
	}
	
	public static void speakAll(Long roomID,String msg){
		ChatRoom room=getRoom(roomID);
		if(room!=null){
			room.speakAll(msg);
		}
	}
	public static void joinRoom(IoSession session){
		ChatRoom room=getRoom(0L);
		if(room!=null){
			room.addMember(session);
		}
	}
	
	public static void leaveRoom(IoSession session){
		Long roomID=(Long) session.getAttribute("roomID");
		if(roomID!=null){
			ChatRoom room=getRoom(roomID);
			if(room!=null){
				room.remMember(session);
			}
			session.removeAttribute("roomID");
		}
	}
	
	public static ChatRoom getRoom(IoSession session){
		Long roomID=(Long) session.getAttribute("roomID");
		if(roomID!=null){
			return getRoom(roomID);
		}
		return null;
	}
	
	private static ChatRoom getRoom(Long roomID){
		return rooms.get(roomID);
	}
	
	public static void createRoom(IoSession session){
		if(!rooms.containsKey(session.getId())){
			ChatRoom room=new ChatRoom(session.getId());
			room.addMember(session);
		}else{
			ChatRoom room=rooms.get(session.getId());
			room.addMember(session);
		}
	}
	
	public static void createRoom(Long roomID){
		if(!rooms.containsKey(roomID)){
			ChatRoom room=new ChatRoom(roomID);
			rooms.put(roomID, room);
		}
	}
	
	public static void destoryRoom(Long roomID){
		ChatRoom room=rooms.get(roomID);
		if(room!=null){
			room.remMemberAll();
			rooms.remove(roomID);
		}
	}
}
